//
//  PublishPreviewViewController.m
//  TryShopping
//
//  Created by LiYinDi on 16/6/15.
//  Copyright © 2016年 RuiBen. All rights reserved.
//

#import "PublishPreviewViewController.h"
#import "TheLoginViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "PublishPreviewJSObject.h"
#import "ShareView.h"
#import "JSONKit.h"
#import "NewMediaPromotionViewController.h"
@interface PublishPreviewViewController ()<ShareViewDelegate,UIGestureRecognizerDelegate>
{
    PulishPreviewModel *model;
    ShareView*SV;
    UIView*shareblackview;
    NSString *headerStr;
    NSString *footerStr;
    NSString *htmlStr;
    NSMutableArray*dicArray;
}
@end

@implementation PublishPreviewViewController
-(void)viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar setHidden:YES];
     [self setAutoLayout];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    dicArray=[NSMutableArray array];
    [self requestPreviewParam];
}
- (IBAction)backBtnClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)requestPreviewParam
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    
    [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
    NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
    [params setObject:Token forKey:@"tokenId"];
    [params setObject:self.titleStr forKey:@"title"];
    [params setObject:self.coverURLStr forKey:@"imageUrl"];
    [params setObject:self.contentStr forKey:@"intro"];
    [params setObject:self.items forKey:@"items"];
    [HttpRequest requestData:@"MediaPromotion/Preview" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        NSLog(@"  ---%@",severDataDict.dataDict);
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                headerStr=[severDataDict.dataDict objectForKey:@"header"];
                footerStr=[severDataDict.dataDict objectForKey:@"footer"];
                htmlStr=[severDataDict.dataDict objectForKey:@"htmlUrl"];
                dicArray=[severDataDict.dataDict objectForKey:@"items"];
                [self setJS];
               
            }
            else
            {
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
                
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    TheLoginViewController *loginVC=[[TheLoginViewController alloc] init];//2.0{9个参数 少2个}
                    [self.navigationController pushViewController:loginVC animated:YES];
                }
//                <img src=“http://www.letuknowit.com/images/wg.png”/>
                

            }
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
    }];
    
    
}
-(void)setJS
{
    
    NSInteger numtime = [NSDate date].timeIntervalSince1970;
    NSString *numtimestr = [NSString stringWithFormat:@"%ld",numtime];
    NSString *uStr=[NSString stringWithFormat:@"%@?time=%@",htmlStr,numtimestr];
    NSURL *urlStr = [NSURL URLWithString:uStr];
    self.shareUrl=uStr;
    [_webView loadRequest:[NSURLRequest requestWithURL:urlStr]];
    
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType

{

    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStr= [NSString stringWithFormat:@"%@", [df stringFromDate:[NSDate date]]];
    NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
    [dict setObject:[user objectForKey:@"userName"] forKey:@"author"];
    [dict setObject:self.titleStr forKey:@"title"];
    [dict setObject:headerStr forKey:@"preCode"];
    [dict setObject:footerStr forKey:@"afterCode"];
    [dict setObject:dateStr forKey:@"date"];
    [dict setValue:dicArray forKey:@"items"];

    NSData *data=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符
    str = [str stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    NSString *js = [NSString stringWithFormat:@"var appData = {}; (function initialize() { appData.getData = function () { var temp =%@; return (temp);};})();", str];
    [webView stringByEvaluatingJavaScriptFromString:js];
    return YES;
}


- (IBAction)pushNowBtnClick:(id)sender {//发布
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
    NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
    [params setObject:Token forKey:@"tokenId"];
    [params setObject:self.titleStr forKey:@"title"];
    [params setObject:self.coverURLStr forKey:@"imageUrl"];
    [params setObject:self.contentStr forKey:@"intro"];
    [params setObject:self.items forKey:@"items"];
    [HttpRequest requestData:@"MediaPromotion/Add" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                 NSLog(@"====%@",severDataDict.dataDict);
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
                self.mpId=[severDataDict.dataDict objectForKey:@"mpId"];
                [self share:self.mpId];//发布成功后分享
       
            }
            else
            {
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    TheLoginViewController *loginVC=[[TheLoginViewController alloc] init];//2.0{9个参数 少2个}
                    [self.navigationController pushViewController:loginVC animated:YES];
                }
                
            }
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
    }];

}
-(void)closeKeyBoad
{
    [self.window makeKeyWindow];
    self.window.hidden=YES;
    [SV removeFromSuperview];
    
}
-(void)cancel:(NSString *)cancel{
    [self closeKeyBoad];
}
-(void)share:(NSString*)mpIdStr{//分享
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"custom" forKey:@"contentType"];
    [param setValue:mpIdStr forKey:@"contentId"];
    [param setValue:@"wx_single" forKey:@"shareTarget"];
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"Company/getShareUrl" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            
            NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
                [self.window makeKeyAndVisible];
                shareblackview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
                shareblackview.backgroundColor=[UIColor blackColor];
                shareblackview.alpha=0.65;
                [self.window addSubview:shareblackview];
                
                SV = [[ShareView alloc]initWithFrame:CGRectMake(0, ScreenHeight-245, ScreenWidth,245)];
                SV.dataDict=severDataDict.dataDict;
                SV.mDelegate=self;
                [self.window addSubview:SV];
                
                UITapGestureRecognizer *singleFingerOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyBoad)];
                singleFingerOne.numberOfTouchesRequired = 1; //手指数
                singleFingerOne.numberOfTapsRequired = 1; //tap次数
                singleFingerOne.delegate = self;
                [shareblackview addGestureRecognizer:singleFingerOne];
                }else{
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:[severDataDict.dataDict objectForKey:@"ResultString"] view:self.view];
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];
}
-(void)successfullyReturns:(NSString *)successfullyReturns{//分享成功后回调登记接口
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"custom" forKey:@"contentType"];
    [param setValue:self.mpId forKey:@"contentId"];
    [param setValue:@"wx_single" forKey:@"shareTarget"];
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"Company/ShareRecords/Add" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                [self closeKeyBoad];
                NewMediaPromotionViewController *loginVC=[[NewMediaPromotionViewController alloc] init];
                [self.navigationController pushViewController:loginVC animated:YES];

            }else{
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:[severDataDict.dataDict objectForKey:@"ResultString"] view:self.view];
                }
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];
}
-(void)setAutoLayout
{
    [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(self.view.mas_top);
        make.height.equalTo(@64);
    }];
    
    [_topLineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_topView.mas_left) ;
        make.right.equalTo(_topView.mas_right) ;
        make.height.equalTo(@1) ;
        make.bottom.equalTo(_topView.mas_bottom);
    }];

    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_topView.mas_centerX);
        make.height.equalTo(@30);
        make.width.equalTo(@110);
        make.top.equalTo(_topView.mas_top).with.offset(25);
    }];
    
    [_backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_titleLabel.mas_centerY);
        make.height.equalTo(@30);
        make.width.equalTo(@60);
        make.left.equalTo(_topView.mas_left);
    }];
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.right.equalTo(self.view.mas_right) ;
        make.top.equalTo(_topView.mas_bottom) ;
        make.bottom.equalTo(_publishNowBtn.mas_top);
    }];
    [_publishNowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.right.equalTo(self.view.mas_right) ;
        make.height.equalTo(@48) ;
        make.bottom.equalTo(self.view.mas_bottom);
    }];

}

@end
